package com.yx.fsysserver.user.service;

import com.yx.fsysserver.common.BaseService;
import com.yx.fsysserver.common.result.JsonPageResult;
import com.yx.fsysserver.user.dao.UserMapper;
import com.yx.fsysserver.user.domain.User;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by liukailong on 2017/2/9.
 */
@Service
public class UserService extends BaseService<User> {
    private final static Logger log = LoggerFactory.getLogger(UserService.class);

    @Autowired
    private UserMapper userMapper;

    @Resource(name = "userMapper")
    public void setUserMapper(UserMapper userMapper) {
        setMapper(userMapper);
        this.userMapper = userMapper;
    }

    public User findUserByUsername(String username){
        User queryObj = new User();
        queryObj.setAccount(username);
        User user = this.userMapper.selectOne(queryObj);
        return user;

    }

    @Transactional
    public void updateUser(){
        User queryObj = new User();
        queryObj.setId(1l);
        queryObj.setTel("222");
        this.userMapper.updateByPrimaryKeySelective(queryObj);

        User queryObj1 = new User();
        queryObj1.setId(21l);
        queryObj1.setTel("21");
        this.userMapper.updateByPrimaryKeySelective(queryObj1);
    }


    public JsonPageResult getList(int pageNo, int pageSize, String keyword) {
        Example example = new Example(User.class);
        example.setOrderByClause("id desc ");
        Example.Criteria criteria = example.createCriteria();
        Example.Criteria orCriteria = example.or();

        if (!StringUtils.isEmpty(keyword)) {
            criteria.andLike("account", "%" + keyword + "%");
            orCriteria.andLike("name", "%" + keyword + "%");
        }

        Page page = PageHelper.startPage(pageNo, pageSize);
        List<User> list = userMapper.selectByExample(example);
        JsonPageResult jsonResultPage = new JsonPageResult(list, page);
        return jsonResultPage;

    }

}
